<template>
  <div class="schedule-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <h2>医生排班预览</h2>
          <div class="header-actions">
            <el-button type="primary" @click="exportSchedule" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出本周排班
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件和统计卡片 -->
      <div class="filter-container">
        <el-select 
          v-model="selectedDepartment" 
          placeholder="请选择科室" 
          @change="handleDepartmentChange"
          style="width: 200px"
          clearable
        >
          <el-option
            v-for="dept in departments"
            :key="dept.department_id"
            :label="dept.department_name"
            :value="dept.department_id"
          />
        </el-select>

        <el-date-picker
          v-model="currentWeek"
          type="week"
          format="YYYY 第 WW 周"
          value-format="YYYY-MM-DD"
          placeholder="选择周"
          @change="fetchScheduleData"
          style="width: 220px; margin-left: 15px"
        />
      </div>

      <!-- 统计卡片 -->
      <div class="stats-container">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6" v-for="stat in stats" :key="stat.title">
            <el-card shadow="hover" class="stat-card">
              <div class="stat-content">
                <div class="stat-icon" :style="{ backgroundColor: stat.color }">
                  <el-icon :size="24"><component :is="stat.icon" /></el-icon>
                </div>
                <div class="stat-info">
                  <div class="stat-title">{{ stat.title }}</div>
                  <div class="stat-value">{{ stat.value }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 排班表格 -->
      <div class="schedule-table">
        <el-table 
          :data="scheduleData" 
          border 
          style="width: 100%" 
          v-loading="loading"
          :empty-text="emptyText"
        >
          <el-table-column prop="date" label="日期" width="120" fixed />
          <el-table-column prop="weekday" label="星期" width="100" fixed>
            <template #default="{ row }">
              <span :class="{'weekend': row.weekday === '星期六' || row.weekday === '星期日'}">
                {{ row.weekday }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="上午 (08:00-12:00)" min-width="300">
            <template #default="{ row }">
              <div v-if="row.amSchedules.length > 0" class="time-slot">
                <div v-for="(schedule, index) in row.amSchedules" :key="index" class="schedule-item">
                  <el-popover placement="right" width="300" trigger="hover">
                    <template #reference>
                      <div class="doctor-card">
                        <el-avatar :size="40" :src="schedule.doctor_img" class="doctor-avatar" />
                        <div class="doctor-info">
                          <div class="doctor-name">{{ schedule.doctor_name }}</div>
                          <div class="doctor-title">{{ schedule.doctor_title }}</div>
                          <div class="doctor-room">
                            <el-icon><Location /></el-icon>
                            {{ schedule.room }}
                          </div>
                        </div>
                      </div>
                    </template>
                    <div class="doctor-detail">
                      <div class="detail-header">
                        <el-avatar :size="60" :src="schedule.doctor_img" />
                        <div class="detail-title">
                          <h3>{{ schedule.doctor_name }}</h3>
                          <p>{{ schedule.doctor_title }} | {{ schedule.department_name }}</p>
                        </div>
                      </div>
                      <el-divider />
                      <div class="detail-body">
                        <p><el-icon><User /></el-icon> <span>性别:</span> {{ schedule.sex }}</p>
                        <p><el-icon><Phone /></el-icon> <span>电话:</span> {{ schedule.telephone }}</p>
                        <p><el-icon><Briefcase /></el-icon> <span>工作经验:</span> {{ schedule.work_year }}年</p>
                        <p><el-icon><School /></el-icon> <span>学历:</span> {{ schedule.education }}</p>
                        <p><el-icon><Document /></el-icon> <span>简介:</span> {{ schedule.introduction || '暂无简介' }}</p>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
              <div v-else class="no-schedule">
                <el-empty description="无排班" :image-size="50" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="下午 (14:00-18:00)" min-width="300">
            <template #default="{ row }">
              <div v-if="row.pmSchedules.length > 0" class="time-slot">
                <div v-for="(schedule, index) in row.pmSchedules" :key="index" class="schedule-item">
                  <el-popover placement="right" width="300" trigger="hover">
                    <template #reference>
                      <div class="doctor-card">
                        <el-avatar :size="40" :src="schedule.doctor_img" class="doctor-avatar" />
                        <div class="doctor-info">
                          <div class="doctor-name">{{ schedule.doctor_name }}</div>
                          <div class="doctor-title">{{ schedule.doctor_title }}</div>
                          <div class="doctor-room">
                            <el-icon><Location /></el-icon>
                            {{ schedule.room }}
                          </div>
                        </div>
                      </div>
                    </template>
                    <div class="doctor-detail">
                      <div class="detail-header">
                        <el-avatar :size="60" :src="schedule.doctor_img" />
                        <div class="detail-title">
                          <h3>{{ schedule.doctor_name }}</h3>
                          <p>{{ schedule.doctor_title }} | {{ schedule.department_name }}</p>
                        </div>
                      </div>
                      <el-divider />
                      <div class="detail-body">
                        <p><el-icon><User /></el-icon> <span>性别:</span> {{ schedule.sex }}</p>
                        <p><el-icon><Phone /></el-icon> <span>电话:</span> {{ schedule.telephone }}</p>
                        <p><el-icon><Briefcase /></el-icon> <span>工作经验:</span> {{ schedule.work_year }}年</p>
                        <p><el-icon><School /></el-icon> <span>学历:</span> {{ schedule.education }}</p>
                        <p><el-icon><Document /></el-icon> <span>简介:</span> {{ schedule.introduction || '暂无简介' }}</p>
                      </div>
                    </div>
                  </el-popover>
                </div>
              </div>
              <div v-else class="no-schedule">
                <el-empty description="无排班" :image-size="50" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { Download, Location, User, Phone, Briefcase, School, Document } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import isoWeek from 'dayjs/plugin/isoWeek'

// 扩展 dayjs 插件
dayjs.extend(weekOfYear)
dayjs.extend(isoWeek)

// 数据定义
const departments = ref([])
const selectedDepartment = ref(null)
const currentWeek = ref(dayjs().format('YYYY-MM-DD'))
const scheduleData = ref([])
const doctors = ref([])
const loading = ref(false)
const exportLoading = ref(false)

// 星期映射
const weekdayMap = {
  '1': '星期一',
  '2': '星期二',
  '3': '星期三',
  '4': '星期四',
  '5': '星期五',
  '6': '星期六',
  '7': '星期日'
}

// 统计卡片数据
const stats = computed(() => {
  const totalDoctors = doctors.value.length
  const totalSchedules = scheduleData.value.reduce((sum, day) => {
    return sum + day.amSchedules.length + day.pmSchedules.length
  }, 0)
  const workingDays = scheduleData.value.filter(day => 
    day.amSchedules.length > 0 || day.pmSchedules.length > 0
  ).length
  const avgPerDay = totalSchedules > 0 ? (totalSchedules / workingDays).toFixed(1) : 0

  return [
    {
      title: '科室医生数',
      value: totalDoctors,
      icon: 'User',
      color: '#409EFF'
    },
    {
      title: '本周排班总数',
      value: totalSchedules,
      icon: 'Calendar',
      color: '#67C23A'
    },
    {
      title: '排班天数',
      value: workingDays,
      icon: 'Date',
      color: '#E6A23C'
    },
    {
      title: '日均排班',
      value: avgPerDay,
      icon: 'TrendCharts',
      color: '#F56C6C'
    }
  ]
})

// 空状态提示
const emptyText = computed(() => {
  if (!selectedDepartment.value) return '请选择科室'
  if (loading.value) return '加载中...'
  return '暂无排班数据'
})

// 获取一级科室列表
const fetchDepartments = async () => {
  try {
    const response = await axios.get('http://localhost:8080/hospital5_war/department/findByLeve?leve=1')
    departments.value = response.data
    if (departments.value.length > 0) {
      selectedDepartment.value = departments.value[0].department_id
      fetchDoctorsByDepartment()
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('获取科室列表失败')
  }
}

// 根据科室ID获取医生列表
const fetchDoctorsByDepartment = async () => {
  if (!selectedDepartment.value) return
  
  try {
    loading.value = true
    const response = await axios.get(`http://localhost:8080/hospital5_war/doctor/findByDepartId1?depart_id1=${selectedDepartment.value}`)
    doctors.value = response.data
    fetchScheduleData()
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  } finally {
    loading.value = false
  }
}

// 获取排班数据
const fetchScheduleData = async () => {
  if (!selectedDepartment.value || !currentWeek.value) return
  
  try {
    loading.value = true
    // 获取当前周的日期范围
    const weekDates = getWeekDates(currentWeek.value)
    
    // 获取所有医生的排班数据
    const allSchedules = []
    for (const doctor of doctors.value) {
      const response = await axios.get('http://localhost:8080/hospital5_war/doctorWork/findAll')
      const schedules = response.data.filter(item => item.doc_id === doctor.doc_id)
      allSchedules.push(...schedules)
    }
    
    // 构建表格数据
    const tableData = weekDates.map(date => {
      const daySchedules = allSchedules.filter(item => item.day === date.dateStr)
      
      return {
        date: date.dateStr,
        weekday: weekdayMap[date.weekday],
        amSchedules: daySchedules
          .filter(item => item.amwork)
          .map(item => {
            const doctor = doctors.value.find(d => d.doc_id === item.doc_id)
            return {
              ...doctor,
              doctor_id: item.doc_id,
              doctor_name: doctor?.doc_name || '未知',
              doctor_title: doctor?.doc_title || '',
              doctor_img: doctor?.img || '',
              department_name: departments.value.find(d => d.department_id === selectedDepartment.value)?.department_name || '',
              room: item.amwork,
              introduction: doctor?.introduction || ''
            }
          }),
        pmSchedules: daySchedules
          .filter(item => item.pmwork)
          .map(item => {
            const doctor = doctors.value.find(d => d.doc_id === item.doc_id)
            return {
              ...doctor,
              doctor_id: item.doc_id,
              doctor_name: doctor?.doc_name || '未知',
              doctor_title: doctor?.doc_title || '',
              doctor_img: doctor?.img || '',
              department_name: departments.value.find(d => d.department_id === selectedDepartment.value)?.department_name || '',
              room: item.pmwork,
              introduction: doctor?.introduction || ''
            }
          })
      }
    })
    
    scheduleData.value = tableData
  } catch (error) {
    console.error('获取排班数据失败:', error)
    ElMessage.error('获取排班数据失败')
  } finally {
    loading.value = false
  }
}

// 获取一周的日期
const getWeekDates = (dateStr) => {
  const result = []
  const d = new Date(dateStr)
  const day = d.getDay() || 7 // 如果是周日，则设为7
  
  // 设置为本周一
  d.setDate(d.getDate() - day + 1)
  
  for (let i = 0; i < 7; i++) {
    const currentDate = new Date(d)
    currentDate.setDate(d.getDate() + i)
    
    const year = currentDate.getFullYear()
    const month = String(currentDate.getMonth() + 1).padStart(2, '0')
    const day = String(currentDate.getDate()).padStart(2, '0')
    
    result.push({
      date: currentDate,
      dateStr: `${year}-${month}-${day}`,
      weekday: String(currentDate.getDay() === 0 ? 7 : currentDate.getDay())
    })
  }
  
  return result
}

// 科室变更处理
const handleDepartmentChange = () => {
  fetchDoctorsByDepartment()
}

// 导出排班表
const exportSchedule = async () => {
  try {
    exportLoading.value = true
    // 这里可以替换为实际的导出逻辑
    // 例如生成Excel或PDF文件
    const departmentName = departments.value.find(d => d.department_id === selectedDepartment.value)?.department_name || '未知科室'
    const week = dayjs(currentWeek.value).format('YYYY年第WW周')
    
    // 模拟导出延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(`已导出${departmentName} ${week} 的排班表`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出排班表失败')
  } finally {
    exportLoading.value = false
  }
}

// 初始化
onMounted(() => {
  fetchDepartments()
})
</script>

<style scoped>
.schedule-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.stats-container {
  margin-bottom: 20px;
}

.stat-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #303133;
}

.schedule-table {
  margin-top: 20px;
}

.time-slot {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.schedule-item {
  margin: 5px 0;
}

.doctor-card {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 6px;
  transition: all 0.3s;
  cursor: pointer;
}

.doctor-card:hover {
  background-color: #f0f7ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.doctor-avatar {
  margin-right: 12px;
}

.doctor-info {
  flex: 1;
}

.doctor-name {
  font-weight: bold;
  margin-bottom: 3px;
}

.doctor-title {
  font-size: 12px;
  color: #666;
  margin-bottom: 3px;
}

.doctor-room {
  font-size: 12px;
  color: #409EFF;
  display: flex;
  align-items: center;
}

.no-schedule {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #999;
}

.weekend {
  color: #F56C6C;
}

.doctor-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.detail-title {
  margin-left: 15px;
}

.detail-title h3 {
  margin: 0;
  font-size: 18px;
}

.detail-title p {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.detail-body p {
  display: flex;
  align-items: center;
  margin: 8px 0;
  font-size: 14px;
}

.detail-body span {
  display: inline-block;
  width: 60px;
  color: #909399;
}

.detail-body .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .stat-card {
    margin-bottom: 10px;
  }
}
</style>
